from flask import request, json, send_from_directory
from sysfunctions import open_database, close_database, get_pic_count
import sysfunctions as sysfunc
import os


#region 登录验证相关
    
# 登录接口
def login():
    data = request.json
    name = data['name']
    # 首先查询名称是否重复
    sql = '''
    select id, picid from UserInfo
    where name = ?;
    '''
    try:
        db = open_database()
        db[1].execute(sql, (name,))
        idList = db[1].fetchall()
        close_database(db)
    except Exception as e:
        return {
            'status': -1,
            'msg': str(e)
        }
    if len(idList) != 0:
        return {
            'status': 0,
            'msg': '登录成功',
            'id': idList[0][0],
            'picid': idList[0][1]
        }
    else:
        sql = '''
        insert into UserInfo(name, picid, gamestatus)
        values(?,?,?);
        '''
        try:
            db = open_database()
            db[1].execute(sql, (name, -1 if not data['picid'] else data['picid'], 0))
            db[0].commit()
            close_database(db)
        except Exception as e:
            return {
                'status': -1,
                'msg': str(e)
            }
        # 获取userId
        sql = '''
        select id, picid from UserInfo
        where name = ?;
        '''
        try:
            db = open_database()
            db[1].execute(sql, (name,))
            userId = db[1].fetchall()
            close_database(db)
            print(userId)
            return {
            'status': 0,
            'msg': '登录成功',
            'id': userId[0][0],
            'picid': userId[0][1]
            }
        except Exception as e:
            return {
                "status": 0, 
                'msg': str(e)
            }

# 获取用户信息
def get_user_info():
    data = request.json
    try:
        if 'id' not in data:
            return {
                'status': -1,
                'msg': 'id未提供'
            }
        sql = '''
            select name, picid from UserInfo
            where id = ?;
        '''
        db = open_database()
        db[1].execute(sql, (data['id'],))
        infoList = db[1].fetchall()
        close_database(db)
        if not infoList or not infoList[0]:
            return {
                'status': -1,
                'msg': '用户不存在'
            }
        else:
            return {
                'status': 0,
                'name': infoList[0][0],
                'picId': infoList[0][1]
            }
    except Exception as e:
        return {
            'status': -1,
            'msg': str(e)
        }

# 落座接口
def sitdown(contest, states):
    try:
        data = request.json
        if 'pos' not in data or 'id' not in data:
            return {
                'status': -1,
                'msg': '请正确传递参数'
            }
        pos, id = data['pos'], data['id']

        # 检查用户是否可以落座
        if contest.seatsA == id or contest.seatsB == id:
            return {
                'status': -1,
                'msg': '请勿重复落座'
            }
        if pos == 1 and contest.seatsA != -1 or pos == 2 and contest.seatsB != -1:
            return {
                'status': -1,
                'msg': '座位已被占用'
            }
        if pos == 1:
            contest.seatsA = id
        elif pos == 2:
            contest.seatsB = id
        states.sendAll()
        return {
            'status': 0,
            'chessKey': contest.chessKey
        }
    except Exception as e:
            return {
                'status': -1,
                'msg': str(e)
            }

# 离座接口
def get_up(contest, states):
    data = request.json
    try:
        id = data['id']
        tempid = [-1, -1]
        if contest.seatsA != id and contest.seatsB != id:
            return {
                'status': -1,
                'msg': '未上座'
            }
        elif contest.seatsA == id:
            tempid[1] = contest.seatsB
        else:
            tempid[0] = contest.seatsA
        contest.init()
        contest.seatsA, contest.seatsB = tempid[0], tempid[1]
        states.sendAll()
        return {
            'status': 0,
            'msg': '离座成功'
        }
    except Exception as e:
        return {
            'status': -1,
            'msg': str(e)
        }

def get_contest(contest):
    try:
        return {
            'status': 0,
            'chessRight': contest.chessRight,
            'chessdata': json.dumps(contest.boardData),
            'step': contest.step,
            'seatsA': contest.seatsA,
            'seatsB': contest.seatsB,
            'gameStatus': contest.check_game_status(),
            'winner': contest.winner
        }
    except Exception as e:
        return {
            'status': -1,
            'msg': str(e)
        }
#endregion

# 下棋
def put_chess(contest, states):
    data = request.json
    try:
        step, chessStatus, chessdata,chessKey = data['step'], data['chessStatus'], data['chessdata'], data['chessKey']
        if contest.gameStatus == False:
            return {
                'status': -1,
                'msg': '对局未开始'
            }
        if step != contest.step:
            return {
                'status': -1,
                'msg': '步数错误'
            }
        if chessStatus != contest.chessRight:
            return {
                'status': -1,
                'msg': '棋权不足'
            }
        contest.put_chess(chessdata)
        states.sendAll()
        return {
            'status': 0,
            'msg': '成功'
        }
    except Exception as e:
        return {
            'status': -1,
            'msg': str(e)
        }

#region 文件相关
def upload_pic():
    try:
        filecount = get_pic_count()
        filedata = request.files['file']
        filedata.save('./static/images/' + str(filecount) + '.gif')
        return {
            'status': 0,
            'msg': "上传成功",
            "picId": filecount
        }

    except Exception as e:
        print(str(e))
        return {
            'statua': -1,
            'msg': str(e)
        }
    
#endregion

#region 系统接口
# 删除所有用户
def clear_all_users():
    data = request.json
    if 'pwd' not in data:
        return {
            'status': -1,
            'msg': '请输入密码'
        }
    elif data['pwd'] != 'woshigedashabi':
        return {
            'status': -1,
            'msg': '密码错误'
        }
    sql = '''
    delete from UserInfo;
    '''
    try:
        db = open_database()
        db[1].execute(sql)
        db[0].commit()
        close_database(db)
    except Exception as e:
        return {
            'status': -1,
            'msg': str(e)
        }
    return {
        'status': 0,
        'msg': '所有用户已删除'
    }

def get_images():
    try:
        data = request.args.get('picId')
        folder = './static/images/'
        return send_from_directory(folder, str(data) + '.gif')
    except:
        return ''

def init_contest(contest, states):
    contest.init()
    states.sendAll()
    #states[1] = True
    return {
        'status': 0,
        'msg': '初始化对局完成'
    }
#endregion
